package protocol.httpclient;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.AsciiString;

import java.net.URI;
import java.nio.charset.StandardCharsets;

public class HttpClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        URI uri = new URI("/k8s/nodes");
        DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString());
        request.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        request.headers().add(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());
        request.headers().add(HttpHeaderNames.USER_AGENT, AsciiString.cached("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"));
        request.headers().add(HttpHeaderNames.COOKIE, "csrftoken=LU9nXiewZe7upU1A1yUXbwl0AYJGz6CcfsA3XrhKDhmgm0sOC27pxAQFMqJS8aX1; sessionid=6fx40cnhadgpvo5u46d65unwwmomu4bq");
        request.headers().add(HttpHeaderNames.HOST,"ath.techfuser.net");
        ctx.writeAndFlush(request);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("msg ->" + msg + "\r\n");

        if (msg instanceof FullHttpResponse) {
            FullHttpResponse response = (FullHttpResponse) msg;

            ByteBuf buf = response.content();
            System.out.println("response -> " + buf.toString(StandardCharsets.UTF_8));
        }
    }
}
